package com.server.web.controller.tool;

import com.alibaba.fastjson.JSON;
import com.server.biz.sms.ChuangLanSmsUtil;
import com.server.biz.sms.SmsSendRequest;
import com.server.biz.sms.SmsSendResponse;
import com.server.common.constant.Constants;
import com.server.common.core.controller.BaseController;
import com.server.common.core.redis.RedisCache;
import com.server.common.utils.DateUtils;
import com.server.common.utils.ServletUtils;
import com.server.common.utils.ip.IpUtils;
import com.server.web.model.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 *
 * @author liutao
 */
@Api(tags = "短信验证码及验证")
@RestController
@RequestMapping("/api/sms")
public class SMSController extends BaseController
{

    @Autowired
    private RedisCache redisCache;

    @Value("${sms.url}")
    private String url;

    @Value("${sms.account}")
    private String account;

    @Value("${sms.password}")
    private String password;

    @Value("${sms.smssign}")
    private String sign;


    @ApiOperation("发送短信验证码")
    @PostMapping(value = "/sendVcodes")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号码", dataType = "String", dataTypeClass = String.class)
    })
    public AjaxResult sendVcode(@RequestParam(value = "phoneNumber") String phoneNumber)
    {
        if(!Pattern.compile("^[1]\\d{10}$").matcher(phoneNumber).matches()){
            return AjaxResult.error("手机号码不合法");
        }
        String date = DateUtils.getTime();
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        if(redisCache.getCacheObject(ip+phoneNumber+"_sendVcodes")!=null){
            System.out.println(date+  ip+phoneNumber+"_sendVcodes"+"---------------------【"+phoneNumber+"过于频繁,请稍后再试】--------------------");
            return AjaxResult.error("过于频繁,请稍后再试！");
        }
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        //限制频繁发送
        redisCache.setCacheObject(ip+phoneNumber+"_sendVcodes", verifyCode, 1, TimeUnit.MINUTES);

        System.out.println(ip+"---------------------【"+date+"、"+  phoneNumber+"短信验证码】--------------------"+verifyCode);
        String msg = sign+"您的验证码是："+verifyCode+"，有效期为5分钟。为了保护您的账号安全，请不要把验证码透露给他人。";
        //短信通知
        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, phoneNumber, "true");
        String requestJson = JSON.toJSONString(smsSingleRequest);
        System.out.println(date+"【短信验证码】-----------------------before request string is: " + requestJson);

        String response = ChuangLanSmsUtil.sendSmsByPost(url, requestJson);
        System.out.println(date+"【短信验证码】-----------------------response after request result is :" + response);

//        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

        redisCache.setCacheObject(phoneNumber+"_verifyCode", verifyCode, Constants.VERIFYCODE_EXPIRATION, TimeUnit.MINUTES);
        return AjaxResult.success();
    }


    @ApiOperation("验证短信")
    @PostMapping(value = "/VerifySMSCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "vcode", value = "短信验证码", dataType = "String", dataTypeClass = String.class),
    })
    public AjaxResult VerifySMSCode(@RequestParam(value = "phoneNumber") String phoneNumber, @RequestParam(value = "vcode") String vcode)
    {
        String date = DateUtils.getTime();
        if(!Pattern.compile("^[1]\\d{10}$").matcher(phoneNumber).matches()){
            return AjaxResult.error("手机号码不合法");
        }
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());

        if(redisCache.getCacheObject(ip+"_login")!=null){
            return AjaxResult.error("操作频繁,请稍后再试！");
        }
        //限制频繁登录
        redisCache.setCacheObject(ip+"_login", DateUtils.parseDateToStr("yyyy-MM-dd mm:HH:ss",new Date()), 5, TimeUnit.SECONDS);
        String verifyCode = redisCache.getCacheObject(phoneNumber+"_verifyCode");
        if(verifyCode!=null && verifyCode.equals(vcode)){
            String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
            redisCache.setCacheObject(phoneNumber+"_token", uuid, 7, TimeUnit.DAYS);
            return AjaxResult.success("验证成功");
        }else {
            System.out.println(date+"【验证短信】-----------------------response  toString is : 验证失败！验证码不匹配");
            return AjaxResult.error(10001,"验证失败！验证码不匹配。");
        }
    }


}
